﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.DCompany;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.DCompany
{
    /// <summary>
    /// 深加工企业的新增
    /// </summary>
    public class AddDcompanyCommandHandle:IRequestHandler<AddDcompanyCommand,APIResult<int>>
    {
        private readonly IBaseRepository<DeepCompany_Model> DCDal;
        private readonly IMapper mapper;
        public AddDcompanyCommandHandle(IBaseRepository<DeepCompany_Model> dCDal, IMapper mapper)
        {
            DCDal = dCDal;
            this.mapper = mapper;
        }

        public Task<APIResult<int>> Handle(AddDcompanyCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var model = mapper.Map<DeepCompany_Model>(request);
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = DCDal.Add(model).Result;
                tran.Complete();
            }

            if (r > 0)
            {
                result.Code = StateCode.Ok;
                result.Message = "企业信息新增成功";
                return Task.FromResult(result);
            }
            else
            {
                result.Code = StateCode.Faile;
                result.Message = "企业信息新增失败";
                return Task.FromResult(result);
            }
        }

    }
}
